package com.fgchen.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * Created by Administrator on 2018-04-08.
 */
@Configuration
@MapperScan(basePackages = "com.fgchen.mapper.study02", sqlSessionFactoryRef = "study02SqlSessionFactory")
public class AppConfig_Study02 {

    @Bean(name = "study02DataSource")
    @ConfigurationProperties(prefix = "spring.datasource.study02")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }


    @Bean(name = "study02SqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("study02DataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
        ssfb.setDataSource(dataSource);
        /*ssfb.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources(
                        "classpath:mapper/study02*//*.xml"
                )
        );*/
        return ssfb.getObject();
    }

    @Bean(name = "study02TransactionManager")
    public DataSourceTransactionManager transactionManager(@Qualifier("study02DataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "study02SqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("study02SqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}
